﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class PlayerMove : MonoBehaviour {

    public float speed = 3.0f;
    public float sensitivity = 10.0f;//鼠标灵敏度
    public float jumpSpeed = 4.0f;
    public float gravity = 9.8f;
    
    private CharacterController m_characterController;
    private Transform m_eye;
    private Animator m_animator;

    private bool moveable = false;
    private float rotationY = 0f;
    private Vector3 moveDirection = Vector3.zero;

    private void Awake()
    {
        m_characterController = GetComponent<CharacterController>();
        m_eye = GameObject.Find("Eye").transform;
        m_animator = GetComponentInChildren<Animator>();
    }

    public void ReloadAnimator()
    {
        m_animator = GameObject.Find("Body2").GetComponent<Animator>();
    }

    // Use this for initialization
    void Start () {
        
	}
	
	// Update is called once per frame
	void FixedUpdate () {
        if (moveable)
        {
            Turn();
            Move();
        }
	}

    void Turn()
    {

        float mouseX = Input.GetAxis("Mouse X");
        float mouseY = Input.GetAxis("Mouse Y");

        float rotationX = transform.localEulerAngles.y + mouseX * sensitivity;

        transform.localEulerAngles = new Vector3(0f, rotationX, 0f);


        rotationY += mouseY * sensitivity;
        rotationY = Mathf.Clamp(rotationY, -90, 90);

        m_eye.localEulerAngles = new Vector3(-rotationY, 0f, 0f);

        if (mouseX != 0 || mouseY != 0)
        {
            m_animator.SetBool("Walk", true);
        }
        else
        {
            m_animator.SetBool("Walk", false);
        }
    }

    void Move()
    {
        if (m_characterController.isGrounded)
        {
            float horizontal = Input.GetAxis("Horizontal");
            float vertical = Input.GetAxis("Vertical");

            moveDirection = new Vector3(horizontal, 0, vertical);
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= speed;
            if (Input.GetButton("Jump"))
                moveDirection.y = jumpSpeed;

            if (horizontal != 0 || vertical != 0)
            {
                m_animator.SetBool("Walk", true);
            }
            else
            {
                m_animator.SetBool("Walk", false);
            }
        }

        moveDirection.y -= gravity * Time.deltaTime;
        m_characterController.Move(moveDirection * Time.deltaTime);
    }

    public void SetMoveable(bool moveable)
    {
        this.moveable = moveable;
    }
}
